import websockets
import requests
import logging
import json
import platform
import pathlib
import os
import ssl

from config import URL_HTTP, URL_DOWNLOAD, URL_WEBSOCKET, EVENT_TOPIC_TASK_RECEIVED, TEMP_DIR
from event_manager import Event

info = logging.getLogger(__name__).info
err = logging.getLogger(__name__).error


class PrintTask(object):
    """打印任务"""

    def __init__(self, id, copies, createTime, deviceId, fileSender, fileType, filename, printerName, state, *args, **kwargs):
        self.id = id
        self.copies = copies
        self.createTime = createTime
        self.deviceId = deviceId
        self.fileSender = fileSender
        self.fileType = fileType
        self.filename = filename
        self.printerName = printerName
        self.state = state


class TaskDiscover:
    """ Task discover"""

    def __init__(self, eventManager, deviceId):
        self.__eventManager = eventManager
        self._deviceId = deviceId

    async def QueryTask(self):
        url = URL_WEBSOCKET + "/" + self._deviceId
        # 事件对象，查询到有任务，则发布事件
        async with websockets.connect(url) as websocket:
            await websocket.send('来自{}的连接'.format(self._deviceId))
            while True:
                result = await websocket.recv()
                self.resultResolve(result)

    def resultResolve(self, msg):
        print("resolve task:", msg)
        try:
            event = Event(eventTopic=EVENT_TOPIC_TASK_RECEIVED)
            event.dict["task"] = PrintTask(**json.loads(msg))
            self.__eventManager.SendEvent(event)
        except:
            info("收到服务端消息:"+msg)
            pass


class TaskPrinter:
    """ Task download & print """

    def __init__(self):
        logging.basicConfig(level=logging.INFO, format=(
            "%(relativeCreated)04d %(process)05d %(threadName)-10s " "%(levelname)-5s %(msg)s"))
        pass

    # 监听器的处理函数
    def execute(self, data):
        """
            data:event
            处理事件数据
        """
        info("TaskPrinter.printTask called ...")
        printTask = data.dict["task"]

        dev_download_url = URL_DOWNLOAD + '?taskId=' + str(printTask.id)
        info("Download started...")
        r = requests.get(dev_download_url)
        f = open(TEMP_DIR + '/' + printTask.filename, 'wb')
        f.write(r.content)
        f.close()

        self.sendToPrinter(printTask)
        self.finishTask(printTask)

    def sendToPrinter(self, printTask):
        sysstr = platform.system()

        fileName = os.getcwd() + '/' + TEMP_DIR + '/' + printTask.filename

        info("fileName:"+fileName)

        prnCommand = ''
        delCommand = ''

        info('Printing...:' + fileName)

        if(sysstr == "Windows"):
            prnCommand = 'echo '+fileName
            delCommand = 'del /Q "' + fileName + '"'

        elif sysstr == "Linux":
            prnCommand = "lp -U pi %s " % (fileName)
            delCommand = 'rm -rf "' + fileName + '"'

        else:
            info('不支持的操作系统...')
            pass

        info("PRN COMMAND:" + prnCommand)
        os.system(prnCommand)
        info("DEL COMMAND:" + delCommand)
        os.system(delCommand)

    def finishTask(self, printTask):
        url = URL_HTTP+'/ptask/finish'
        info("Finish...")
        requests.post(url, data={'taskId': printTask.id})
